import { apiRequest } from '@/utils/api'
import type {
  Post,
  PostFormData,
  ApiResponse,
  PaginationParams,
  SearchFilters
} from '@/types'

/**
 * 帖子相关API服务
 */
export const postService = {
  /**
   * 创建寻宠帖子
   */
  create: async (data: PostFormData): Promise<ApiResponse<Post>> => {
    return await apiRequest.post('/posts', data)
  },

  /**
   * 获取帖子列表（公开）
   */
  getList: async (filters: SearchFilters, params: PaginationParams): Promise<ApiResponse<Post[]> & { pagination?: any }> => {
    const queryParams = new URLSearchParams({
      page: params.page.toString(),
      limit: params.limit.toString(),
    })

    if (filters.species) queryParams.append('species', filters.species)
    if (filters.color) queryParams.append('color', filters.color)
    if (filters.gender) queryParams.append('gender', filters.gender)
    if (filters.location) queryParams.append('location', filters.location)
    if (filters.dateFrom) queryParams.append('dateFrom', filters.dateFrom)
    if (filters.dateTo) queryParams.append('dateTo', filters.dateTo)
    if (filters.keyword) queryParams.append('keyword', filters.keyword)

    return await apiRequest.get(`/posts?${queryParams}`) as ApiResponse<Post[]> & { pagination?: any }
  },

  /**
   * 获取我的帖子列表
   */
  getMyPosts: async (params: PaginationParams): Promise<ApiResponse<Post[]> & { pagination?: any }> => {
    const queryParams = new URLSearchParams({
      page: params.page.toString(),
      limit: params.limit.toString(),
    })

    return await apiRequest.get(`/posts/my?${queryParams}`) as ApiResponse<Post[]> & { pagination?: any }
  },

  /**
   * 根据ID获取帖子详情
   */
  getById: async (id: number): Promise<ApiResponse<Post>> => {
    return await apiRequest.get(`/posts/${id}`)
  },

  /**
   * 更新帖子信息
   */
  update: async (id: number, data: Partial<PostFormData>): Promise<ApiResponse<Post>> => {
    return await apiRequest.put(`/posts/${id}`, data)
  },

  /**
   * 更新帖子状态
   */
  updateStatus: async (id: number, status: 'searching' | 'found' | 'closed'): Promise<ApiResponse> => {
    return await apiRequest.patch(`/posts/${id}/status`, { post_status: status })
  },

  /**
   * 删除帖子
   */
  delete: async (id: number): Promise<ApiResponse> => {
    return await apiRequest.delete(`/posts/${id}`)
  },
}
